const fileService = require("../service/file.service");
const userService = require("../service/user.service");
const { SERVER_HOST, SERVER_PORT } = require("../config/server");

class FileController {
  async create(ctx, next) {
    // 1、获取相关信息
    const { filename, mimetype, size } = ctx.request.file;
    const { id } = ctx.user;

    try {
      // 2、将图片信息以及id存储起来
      const result = await fileService.create(filename, mimetype, size, id);

      // 3、更新user表的头像地址
      const avatarUrl = `${SERVER_HOST}:${SERVER_PORT}/users/avatar/${id}`;
      const result2 = await userService.updateUserAvatar(avatarUrl, id);
      ctx.body = {
        code: 0,
        message: "上传头像成功~",
        data: avatarUrl,
      };
    } catch (error) {
      console.log(error);
    }
  }
}

module.exports = new FileController();
